import { useEffectRef } from '@/components';
import { forkHandler as fh, uid } from '@/utils';
import { useEffect, useMemo, useState } from 'react';
import useMounted from './useMounted';

function usePromise(promise) {
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);
  const [status, setStatus] = useState(0);
  const isMounted = useMounted();
  const currStatus = useEffectRef(status);

  useEffect(() => {
    const id = uid();
    setStatus(id);
    setResult(null);
    setError(null);
    const isCurrent = () => currStatus.current === id;
    const safeCb = (callback) => fh(isCurrent, isMounted, callback, true);
    promise.then(safeCb(setResult), safeCb(setError)).finally(
      safeCb(() => {
        setStatus(0);
      }),
    );
  }, [promise]);

  return useMemo(() => [result, error, status === 0], [status]);
}

export default usePromise;
